//index.js
//获取应用实例
var app = getApp();
Page({
  data: {
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,
    loadingHidden: false, // loading
    userInfo: {},
    swiperCurrent: 0,
    selectCurrent: 0,
    categories: [],
    activeCategoryId: 0,
    goods: [],
    scrollTop: 0,
    loadingMoreHidden: true,
    hasNoItem:true,
    hasNoCoupons: true,
    coupons: [],
    searchInput: '',
    pintuanList:[],
    curPage: 1,
    pageSize: 10
  },

  tabClick: function(e) {
    this.setData({
      activeCategoryId: e.currentTarget.id,
      curPage: 1
    });
    this.getGoodsList(this.data.activeCategoryId);
  },
  //事件处理函数
  swiperchange: function(e) {
    //console.log(e.detail.current)
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  toDetailsTap: function(e) {
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
    })
  },
  tapBanner: function(e) {
    if (e.currentTarget.dataset.id != 0) {
      wx.navigateTo({
        url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
      })
    }
  },
  bindTypeTap: function(e) {
    this.setData({
      selectCurrent: e.index
    })
  },
  onLoad: function() {
    let that = this;
    wx.setNavigationBarTitle({
      title: wx.getStorageSync('mallName')
    });
    wx.request({
        url: app.globalData.domain + '/wxapp/banner/',
        header: {
          'Authorization': 'JWT ' + wx.getStorageSync('token')
        },
        success: function(res) {
          if (res.data.code == 404) {
            wx.showModal({
              title: '提示',
              content: '请在后台添加 banner 轮播图片',
              showCancel: false
            })
          } else {
            that.setData({
              banners: res.data
            });
          }
        }
      }),
    wx.request({
      url: app.globalData.domain + '/item_cats/',
      header: {
        'Authorization': 'JWT ' + wx.getStorageSync('token')
      },
      data: {
        level: 0
      },
      success: function(res) {
        var categories = [{
          pk: 0,
          name: "全部"
        }];
        if (res.statusCode == 200) {
          for (var i = 0; i < res.data.length; i++) {
            categories.push(res.data[i]);
          }
        }
        that.setData({
          categories: categories,
          activeCategoryId: 0,
          curPage: 1
        });
        that.getGoodsList(0);
      }
    })
    that.getCoupons();
    that.getpintuanList();
    //that.getNotice();
  },

  onPageScroll(e) {
    let scrollTop = this.data.scrollTop
    this.setData({
      scrollTop: e.scrollTop
    })
  },
  getGoodsList: function(categoryId, append) {
    if (categoryId == 0) {
      categoryId = "";
    }
    var that = this;
    wx.showLoading({
      "mask": true
    })
    wx.request({
      url: app.globalData.domain + '/item/',
      header: {
        'Authorization': 'JWT ' + wx.getStorageSync('token')
      },
      data: {
        item_cats__parent__parent: categoryId,
        item_name: that.data.searchInput,
        page: this.data.curPage,
        page_size: this.data.pageSize
      },
      success: function(res) {
        wx.hideLoading()
        if (res.statusCode == 404 || res.statusCode == 700) {
          let newData = {
            loadingMoreHidden: false
          }
          if (!append) {
            newData.goods = []
          }
          that.setData(newData);
          return
        }
        let goods = [];
        if (append) {
          goods = that.data.goods
        }
        for (var i = 0; i < res.data.results.length; i++) {
          goods.push(res.data.results[i]);
        }
        that.setData({
          loadingMoreHidden: true,
          goods: goods,
        });
      }
    })
  },
  getCoupons: function() {
    var that = this;
    wx.request({
      url: app.globalData.domain + '/coupon_tpl/',
      data: {
        //type: ''
      },
      header: {
        'Authorization': 'JWT ' + wx.getStorageSync('token')
      },
      success: function(res) {
        //console.log(res)
        if (res.statusCode == 200 && res.data.length != 0) {
          that.setData({
            hasNoCoupons: false,
            coupons: res.data
          });
        }
      }
    })
  },
  gitCoupon: function(e) {
    var that = this;
    wx.request({
      url: app.globalData.domain + '/wxapp/coupon/',
      header: {
        'Authorization': 'JWT ' + wx.getStorageSync('token')
      },
      data: {
        // id: e.currentTarget.dataset.id,
        // token: wx.getStorageSync('token')
        coupon_tpl: e.currentTarget.dataset.id,
      },
      method: 'POST',
      success: function(res) {
        let i = 0
        var coupon_type = 0
        for (i; i < res.data.length; i++) {
          if (e.currentTarget.dataset.id == res.data[i].coupon_tpl)
            coupon_type = res.data[i].coupon_type
        }

        if (res.statusCode == 201) {
          wx.showToast({
            title: '领取成功，赶紧去下单吧~',
            icon: 'success',
            duration: 2000
          })
        } else {
          wx.showModal({
            title: '错误',
            content: res.data.detail,
            showCancel: false
          })
        }

        // if (res.data.code == 20001 || res.data.code == 20002) {
        //   wx.showModal({
        //     title: '错误',
        //     content: '来晚了',
        //     showCancel: false
        //   })
        //   return;
        // }
        //if (res.data.code == 20003) {
        // if (res.statusCode != 200) {
        //   wx.showModal({
        //     title: '错误',
        //     content: '你领过了，别贪心哦~',
        //     showCancel: false
        //   })
        //   return;
        // }
        // if (res.data.code == 30001) {
        //   wx.showModal({
        //     title: '错误',
        //     content: '您的积分不足',
        //     showCancel: false
        //   })
        //   return;
        // }
        //if (res.data.code == 20004) {
        // if (coupon_type == 1) {
        //   wx.showModal({
        //     title: '错误',
        //     content: '已过期~',
        //     showCancel: false
        //   })
        //   return;
        // }
        //if (res.data.code == 0) {
        // if (coupon_type == 2) {
        //   wx.showToast({
        //     title: '领取成功，赶紧去下单吧~',
        //     icon: 'success',
        //     duration: 2000
        //   })
        // } else {
        //   wx.showModal({
        //     title: '错误',
        //     //content: res.data.msg,
        //     showCancel: false
        //   })
        // }
      }
    })
  },
  getpintuanList:function(){
    var that = this;
    
    wx.request({
      url: app.globalData.domain + '/wxapp/bulk_purchase_tpl/',
      header: {
        'Authorization': 'JWT ' + wx.getStorageSync('token')
      },
      success: function (res) {
        //console.log(res.data,"bulk_purchase_tpl",)
        if (res.statusCode == 200 && res.data.length != 0) {
          that.setData({
            hasNoItem: false,
            pintuanList:res.data,
          });
          if (res.data.length>4){
            that.setData({
              pintuanList: res.data.slice(0, 4)
            })
          }
        }
      }
    })
  },
  onShareAppMessage: function() {
    return {
      title: wx.getStorageSync('mallName') + '——' + app.globalData.shareProfile,
      path: '/pages/index/index',
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
  // getNotice: function() {
  //   var that = this;
  //   wx.request({
  //     url: 'https://api.it120.cc/' + app.globalData.subDomain + '/notice/list',
  //     data: {
  //       pageSize: 5
  //     },
  //     success: function(res) {
  //       if (res.data.code == 0) {
  //         that.setData({
  //           noticeList: res.data.data
  //         });
  //       }
  //     }
  //   })
  // },
  listenerSearchInput: function(e) {
    this.setData({
      searchInput: e.detail.value
    })

  },
  toSearch: function() {
    this.setData({
      curPage: 1
    });
    this.getGoodsList(this.data.activeCategoryId);
  },
  onReachBottom: function() {
    this.setData({
      curPage: this.data.curPage + 1
    });
    this.getGoodsList(this.data.activeCategoryId, true)
  },
  onPullDownRefresh: function() {
    this.setData({
      curPage: 1
    });
    this.getGoodsList(this.data.activeCategoryId)
  }
})